package com.tian.print.depot;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.tian.print.R;
import com.tian.print.ZxScanActivity;
import com.tian.print.app.BaseActivity;
import com.tian.print.bean.GoodsModel;
import com.tian.print.http.BaseObserver;
import com.tian.print.http.RxSchedulers;
import com.tian.print.http.request.ApiRequest;

import butterknife.BindView;
import butterknife.OnClick;

public class OutDepotActivity extends BaseActivity {

    private final static String TAG = OutDepotActivity.class.getSimpleName();

    private static final int REQUEST_CODE = 10000;

    /**
     * 仓库名字
     */
    @BindView(R.id.et_stock_name)
    EditText et_stock_name;


    /**
     * 版长
     */
    @BindView(R.id.et_length)
    EditText et_length;

    /**
     * 版号
     */
    @BindView(R.id.et_num)
    EditText et_num;

    /**
     * 周长
     */
    @BindView(R.id.et_girth)
    EditText et_girth;

    private String plateNoOld;
    private GoodsModel goodsModel;

    @BindView(R.id.btn_out_depot)
    Button btn_out_depot;

    private String oldNoValue, currentValue;
    private boolean isNeedRefresh = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_depot);
        showLeftBack();
        setTitleShow("出库信息");

        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i("Out", s + "--start--" + start + ",before--" + before + ",count--" + count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isNeedRefresh && !TextUtils.isEmpty(s.toString())) {
                    if (oldNoValue == null) {
                        plateNoOld = oldNoValue = s.toString();
                    } else {
                        plateNoOld = s.toString().substring(0,s.toString().lastIndexOf(plateNoOld));
                    }

                    Log.i("Out", "plateNoOld--" + plateNoOld);
                    refresh();
                }
            }
        });


    }

    private void initViews() {

        isNeedRefresh = false;

        et_stock_name.setText(goodsModel.getPlace());
        et_length.setText(goodsModel.getBanChang() + "");
        et_num.setText(goodsModel.getPlateNoOld() + "");
        et_girth.setText(goodsModel.getZhouChang() + "");

        oldNoValue = goodsModel.getPlateNoOld() + "";
        isNeedRefresh = true;

        if (goodsModel.getUseState() == 1) {
            btn_out_depot.setText("已出库");
            btn_out_depot.setEnabled(false);
        } else {
            btn_out_depot.setText("出库");
            btn_out_depot.setEnabled(true);
        }
    }


    @OnClick({R.id.btn_out_depot, R.id.btn_out_scan})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_out_depot:
                outDepot();
                break;
            case R.id.btn_out_scan:
                scanQRCode();
                break;
        }
    }

    /**
     * 打开二维码扫描
     * activity需要去重写onactivityforresult方法，具体请参考MainActivity
     */
    public void scanQRCode() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
        integrator.setCaptureActivity(ZxScanActivity.class);
        //底部的提示文字，设为""可以置空
        integrator.setPrompt("请扫描二维码");
        //前置或者后置摄像头
        integrator.setCameraId(0);
        //扫描成功的「哔哔」声，默认开启
        integrator.setBeepEnabled(true);
//                    integrator.setBarcodeImageEnabled(true);//是否保留扫码成功时候的截图
        integrator.initiateScan();
    }


    private void outDepot() {
        ApiRequest.apiClent.outOfStock(plateNoOld, "1")
                .compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Toast.makeText(OutDepotActivity.this, "出库成功", Toast.LENGTH_LONG).show();
                        refresh();
                    }

                    @Override
                    public void onFailure(String msg) {
                        Toast.makeText(OutDepotActivity.this, "出库失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("Ok", "-requestCode-" + requestCode + ",resultCode-" + resultCode);
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null)
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            else
                onZxCodeReturn(result.getContents());
        }
        //
        else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public void onZxCodeReturn(String result) {
        plateNoOld = result;
        refresh();
    }


    private void refresh() {
        if (TextUtils.isEmpty(plateNoOld)) {
            Toast.makeText(this, "版号为空", Toast.LENGTH_SHORT).show();
            finish();
        }

        ApiRequest.apiClent.queryGoods(plateNoOld).compose(RxSchedulers.compose())
                .subscribe(new BaseObserver<GoodsModel>() {
                    @Override
                    public void onSuccess(GoodsModel gm) {
                        goodsModel = gm;
                        initViews();
                    }

                    @Override
                    public void onFailure(String msg) {
                        oldNoValue = plateNoOld;
                        Toast.makeText(OutDepotActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                });
    }

}

